package com.ormlite.activity.tool;

import java.util.List;

import android.app.Activity;
import android.util.SparseIntArray;

import com.ormlite.pojo.Event;
import com.ormlite.pojo.Movie;

public class Utils {

	public static final int NTITLE = 0;
	public static final int NDIRECTOR = 1;
	public static final int NYEAR = 2;
	public static final int NRATE = 3;

	public static final int ACTION_BAR_ITEM_LENGHT = 7;

	private Utils() {
		// no instance needed
	}

	public static Integer toInteger(String number) {
		return "".equals(number) ? null : Integer.parseInt(number);
	}

	public static Double toDouble(String number) {
		return "".equals(number) ? null : Double.parseDouble(number);
	}

	public static boolean checkMovieFields(Movie movie) {
		return movie.getTitle().isEmpty() || movie.getDirector().isEmpty() || movie.getYear() == null;
	}

	public static String getExtraFromActivity(Activity activity, String extra) {
		return activity.getIntent().getExtras().getString(extra);
	}

	public static String truncator(boolean trunc, Object... objects) {
		StringBuilder builder = new StringBuilder();
		builder.append("|--");
		for (Object object : objects) {
			builder.append((trunc) ? trunc(object.toString()) : object.toString());
			builder.append("--|--");
		}
		builder.delete(builder.length() - 5, builder.length());
		builder.append("--|");
		return builder.toString();
	}

	private static String trunc(String string) {
		if (string.length() <= ACTION_BAR_ITEM_LENGHT) {
			return string;
		}
		return string.substring(0, ACTION_BAR_ITEM_LENGHT) + "...";
	}

	public static String[] extractDataFromMovies(boolean trunc, List<Movie> movies, SparseIntArray positionToId) {
		String[] names = new String[movies.size()];
		int i = 0;
		for (Movie movie : movies) {
			positionToId.put(i, movie.getId());
			names[i++] = Utils.truncator(trunc, movie.getTitle(), movie.getDirector(), movie.getYear());
		}
		return names;
	}

	public static String[] extractDataFromEvents(boolean trunc, List<Event> events, SparseIntArray positionToId) {
		String[] names = new String[events.size()];
		int i = 0;
		for (Event event : events) {
			positionToId.put(i, event.getId());
			names[i++] = Utils.truncator(trunc, event.getName(), event.getMovie().getTitle(), event.getTime());
		}
		return names;
	}
}
